
<!-- 
  echarts
  该组件依托于echarts，请确定是否安装
-->
<template>
  <div class="echart_box">
    <div class="loading" v-show="isLoading">数据加载中...</div>
    <div class="nodata" v-show="!isLoading && isOptionAbnormal">数据为空</div>
    <div class="echart_container" v-show="!isLoading && !isOptionAbnormal">
      <div class="echarts" :id="randomId"></div>
    </div>
  </div>
</template>
<script>
import echarts from "echarts";
// import * as echarts from "echarts";
export default {
  name: "echarts",
  props: {
    option: {
      default() {
        return {};
      },
    },
    isLoading: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      myEcharts: null,
      isOptionAbnormal: false,
      randomId: "e-dom" + Date.now() + Math.random(),
    };
  },
  created() {},
  mounted() {
    this.init();
    this.checkAndSetOption();
    window.addEventListener("resize", () => {
      this.myEcharts.resize();
    });
  },
  watch: {
    option: {
      handler: function (newVal, oldVal) {
        this.checkAndSetOption();
      },
      deep: true,
    },
  },
  methods: {
    init() {
      let $echartsDOM = document.getElementById(this.randomId);
      if (!$echartsDOM) return;
      let myEcharts = echarts.init($echartsDOM);
      this.myEcharts = myEcharts;
    },
    isValidOption(option) {
      return (
        this.isObject(option) &&
        !this.isEmptyObject(option) &&
        this.hasSeriesKey(option) &&
        this.isSeriesArray(option) &&
        !this.isSeriesEmpty(option)
      );
    },
    isObject(option) {
      return Object.prototype.isPrototypeOf(option);
    },
    isEmptyObject(option) {
      return Object.keys(option).length === 0;
    },
    hasSeriesKey(option) {
      return !!option["series"];
    },
    isSeriesArray(option) {
      return Array.isArray(option["series"]);
    },
    isSeriesEmpty(option) {
      return option["series"].length === 0;
    },
    checkAndSetOption() {
      let option = this.option;
      if (this.isValidOption(option)) {
        this.myEcharts.setOption(option);
    //     var bmap = myEcharts.getModel().getComponent('bmap').getBMap();
    // bmap.addControl(new BMap.MapTypeControl());
        this.isOptionAbnormal = false;
      } else {
        this.isOptionAbnormal = true;
      }
    },
  },
};
</script>
<style scoped>
.echart_box {
  position: relative;
  height: 100%;
}
.echart_container,
.loading,
.nodata {
  position: absolute;
}
.echart_container,
.echarts {
  width: 100%;
  height: 100%;
}
.nodata,
.loading {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 1rem;
  color: #8590a6;
}
</style>